import { ref } from 'vue';
import { defineStore } from 'pinia';

import { getUserInfoApi, loginApi, logoutApi } from '@/api/user/member';
import type { LoginVo, MemberForm, MemberVO, UserInfo } from '@/api/user/member/types';

export const useUserStore = defineStore(
  'user',
  () => {
    const user = ref<UserInfo>({
      userId: '',
      token: '',
      info: {}
    });

    /*登录*/
    function login(loginData: MemberForm) {
      return new Promise<void>((resolve, reject) => {
        loginApi(loginData)
          .then((response) => {
            // user.value.userId=BigInt(response.data.id).toString();
            console.log(response);
            user.value.userId = response.data.id;
            user.value.token = response.data.token;
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    }

    /*获取用户信息*/
    function getUserInfo(userId: string | number) {
      return new Promise<MemberVO>((resolve, reject) => {
        getUserInfoApi(userId)
          .then(({ data }) => {
            if (data) {
              user.value.info = data;
              return resolve(data);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    }

    /*退出登录*/
    function logout() {
      return new Promise<void>((resolve, reject) => {
        logoutApi()
          .then(() => {
            localStorage.setItem('token', '');
            localStorage.setItem('user', '');

            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    }

    /*移除token*/
    function restToken() {
      return new Promise<void>((resolve) => {
        localStorage.setItem('token', '');
        resolve();
      });
    }

    return {
      login,
      user,
      getUserInfo,
      logout,
      restToken
    };
  },
  {
    persist: true //同步到本地
  }
);
